package cn.itsource.hrm.controller;

import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.utils.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastdfs")
public class FastDfsController {


    /**
     *
     * @param file 必须穿文件，名字为file
     *            springmvc中接收上传文件都用MultipartFile
     * @return 成功与否，还要返回地址，resultObj来存放地址
     */
    @PostMapping
    public AjaxResult upload(@RequestParam(name = "file")MultipartFile file){

        try {
            String fileName = file.getOriginalFilename(); // xxxx.jpg
            String extName = fileName.substring(fileName.lastIndexOf(".")+1);
            String filePath = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(filePath);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上传失败！"+e.getLocalizedMessage());
        }
    }



    /**
     *
     * @param filePath  /group1/xxx 拆分两个 groud xxx/yy...
     * @return
     */
    @DeleteMapping
    public AjaxResult del(@RequestParam(name = "filePath")String filePath){
        try {
            ///goup1/xxxxx/yyyy
            String pathTmp = filePath.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            System.out.println(groupName);
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            System.out.println(remotePath);
            FastDfsUtil.delete(groupName,remotePath);
            return AjaxResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败！"+e.getLocalizedMessage());
        }
    }


}
